package com.myapp.web.struts2.validators;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class MultiFieldStringRequiredValidator extends FieldValidatorSupport{
	
	public static final String FIELD_MESSAGE_KEY = ".required";
	
	private String fields;
	private String allFields[];
	
	private Object validateObject;
	
	@Override
	public void validate(Object object) throws ValidationException {	
		validateObject = object;
		if(allFields == null)
		{
			return;
		}
		for(int i= 0 ; i< allFields.length; i++)
		{
			validateField(allFields[i]);
		}		
	}
	
	@Override
	protected void addFieldError(String field, Object object) {
		String fieldMesageKey = field.concat(FIELD_MESSAGE_KEY);		
		String message = this.getValidatorContext().getText(fieldMesageKey, defaultMessage);
		if(message != null)
		{
			getValidatorContext().addFieldError(field,message);
		}else
		{
			super.addFieldError(field, object);
		}
	}
		 
	private boolean validateField(String field) throws ValidationException
	{
        String value = (String)this.getFieldValue(field,validateObject);
        if(value == null || value.trim().length() == 0)
        {
        	addFieldError(field, validateObject);
        	return false;
        }
		return true;
	}
	
	private void resovleFields()
	{
		if(fields == null || fields.trim().length() == 0)
		{
			return ;
		}
		allFields = fields.split(",");
	}

	public String getFields() {
		return fields;
	}

	public void setFields(String fields) {
		this.fields = fields;
		resovleFields();
	}	
}
